import {
  Catch,
  HttpException,
  ExceptionFilter,
  ArgumentsHost,
} from '@nestjs/common'
import { Response } from 'express'

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(execption: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const response = ctx.getResponse<Response>()
    const status = execption.getStatus()
    const message = execption.message

    const execptionResponse: any = execption.getResponse()
    let validatorMessage = execptionResponse
    if (typeof validatorMessage === 'object') {
      validatorMessage = execptionResponse.message[0]
    }

    response.status(status).json({
      code: status,
      message: validatorMessage || message,
    })
  }
}
